/**
 * Created by sky_wang on 2017/7/18.
 */
REPORT_VIEW.REPORT_CONSULTED = {};
var REPORT_RELATION = REPORT_VIEW.REPORT_CONSULTED;

$(document).ready(function() {
    var container = document.getElementById('jsoneditor');

    var options = {
        mode: 'tree',
        modes: ['code', 'form', 'text', 'tree', 'view'], // allowed modes
        onError: function (err) {
            alert(err.toString());
        },
        onModeChange: function (newMode, oldMode) {
            console.log('切换模式从', oldMode, '到', newMode);
        }
    };
    var editor = new JSONEditor(container, options, {});
    $.ajax({
        type : "get",
        url  : "relation/0",
        data : {},
        async : true,
        success : function(data){
            console.log(data);
            REPORT_RELATION.data = data;
            if (REPORT_RELATION.data["relation_data_config"])
            {
                editor.set(JSON.parse(REPORT_RELATION.data["relation_data_config"]));
            }
            else if (REPORT_RELATION.data["relation_data_default"])
            {
                editor.set(JSON.parse(REPORT_RELATION.data["relation_data_default"]));
            }
            else
            {

            }

        }
    });

    $(".relation_load_default").click(function () {
        if (REPORT_RELATION.data["relation_data_default"])
        {
            editor.set(JSON.parse(REPORT_RELATION.data["relation_data_default"]));
            alert("加载成功！");
        }
    });
    $(".relation_load_run").click(function () {
        if (REPORT_RELATION.data["relation_data_config"])
        {
            editor.set(JSON.parse(REPORT_RELATION.data["relation_data_config"]));
            alert("加载成功！");
        }
    });
    function isJSON(str) {
        if (typeof str == 'string') {
            try {
                JSON.parse(str);
                return true;
            } catch(e) {
                console.log(e);
                return false;
            }
        }
    }
    $(".relation_save").click(function () {
        $.ajax({
            type : "put",
            url  : "relation/0",
            data :  {data:JSON.stringify(
                        {"vid":"0",
                          "relation_data_default":REPORT_RELATION.data["relation_data_default"],
                          "relation_data_config":editor.getText()
                        }
                    )
            },
            async : true,
            success : function(data){
                REPORT_RELATION.data["relation_data_config"] = editor.getText();
                alert("保存成功");
            },
            error: function(e) {
                if (e && e.responseText){
                    alert(e.responseText);
                }
            }
    });
    });
});